#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , timer(new QTimer(this))
    , elapsedSeconds(0)
{
    ui->setupUi(this);

    // 连接按钮点击信号到槽函数
    connect(ui->startButton, &QPushButton::clicked, this, &Widget::on_startButton_clicked);
    connect(ui->stopButton, &QPushButton::clicked, this, &Widget::on_stopButton_clicked);
    connect(ui->resetButton, &QPushButton::clicked, this, &Widget::on_resetButton_clicked);
    connect(timer, &QTimer::timeout, this, &Widget::updateTimer);

    // 初始化计时器
    timer->setInterval(1000); // 设置计时间隔1秒
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_startButton_clicked()
{
    //检查定时器是否正在运行
    if (!timer->isActive()) {
        this->updateTimer();//立即启动
        timer->start();
    }
}

void Widget::on_stopButton_clicked()
{
    timer->stop();
}

void Widget::on_resetButton_clicked()
{
    timer->stop();
    elapsedSeconds = 0;
    ui->timeLabel->setText("00:00");
}

void Widget::updateTimer()
{
    ++elapsedSeconds;
    int minutes = elapsedSeconds / 60;
    int seconds = elapsedSeconds % 60;
//确保分钟和秒数总是以两位数的形式显示，不足两位时前面补 0
    QString timeText = QString("%1:%2")
                           .arg(minutes, 2, 10, QLatin1Char('0'))
                           .arg(seconds, 2, 10, QLatin1Char('0'));
    ui->timeLabel->setText(timeText);
}
